#include "Channel.hpp"
#include "EventLoop.hpp"

#include <sys/epoll.h>
#include <cassert>

Channel::Channel(EventLoop* loop, int fd)
    : loop_(loop), fd_(fd), events_(0), revents_(0), inPoller_(false) {}

Channel::~Channel() = default;

void Channel::handleEvent() {
    if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN)) {
        if (closeCallback_) closeCallback_();
    }
    if (revents_ & (EPOLLERR)) {
        if (errorCallback_) errorCallback_();
    }
    if (revents_ & (EPOLLIN | EPOLLPRI)) {
        if (readCallback_) readCallback_();
    }
    if (revents_ & EPOLLOUT) {
        if (writeCallback_) writeCallback_();
    }
}

void Channel::enableReading() {
    events_ |= EPOLLIN;
    update();
}

void Channel::enableWriting() {
    events_ |= EPOLLOUT;
    update();
}

void Channel::disableWriting() {
    events_ &= ~EPOLLOUT;
    update();
}

void Channel::disableAll() {
    events_ = 0;
    update();
}

bool Channel::isWriting() const {
    return events_ & EPOLLOUT;
}

void Channel::update() {
    // 通知 EventLoop 更新该 channel
    // 实际调用 loop->updateChannel(this); (后续完成)
    assert(loop_ != nullptr);
    loop_->updateChannel(this); // 接口预留，后面我们实现 EventLoop 时会处理
}

void Channel::remove() {
    assert(loop_ != nullptr);
    loop_->removeChannel(this);
}
